package com.ellecity06.cwhiskymall.ui.login

import androidx.lifecycle.viewModelScope
import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.ktx.md5Encrypt
import com.ellecity06.common.ktx.postEvent
import com.ellecity06.common.utils.CommonUtils
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.appContext
import com.ellecity06.cwhiskymall.bean.request.LoginRequest
import com.ellecity06.cwhiskymall.bean.request.SendSmsCodeRequest
import com.ellecity06.cwhiskymall.bean.request.VersionInfoRequest
import com.ellecity06.cwhiskymall.helper.JPushHelper
import com.ellecity06.cwhiskymall.http.ServerConfig
import com.ellecity06.cwhiskymall.http.request
import com.ellecity06.cwhiskymall.storage.AppStorage
import com.ellecity06.cwhiskymall.storage.UserStorage
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2023/4/13 16:10
 * @des
 */
class LoginViewModel : BaseMviViewModel<LoginState, LoginIntent>() {
    private var checked: Boolean = false
    private val versionCode: Int by lazy { CommonUtils.getVersionCode(appContext) }

    /**
     * 登录方式 0- 密码 1-验证码
     */
    private var loginType = 0

    override suspend fun collectIntent(it: LoginIntent) {
        when (it) {
            is LoginIntent.ChangeCheck -> {
                checked = !checked
                mState.postEvent(LoginState.Checked(checked))
            }
            // 获取图片验证码
            is LoginIntent.SendSmsCode -> fetchSmsCode(it.imageCode, it.phone)
            is LoginIntent.Login -> login(it)
            LoginIntent.FetchLastVersion -> {
                lastVersion()
            }
            is LoginIntent.GetPicCode -> getPicCode(it.phone)
            else -> {}
        }
    }


    private fun login(it: LoginIntent.Login) {
        if (it.phone.isEmpty() || it.phone.length < 11) {
            ToastUtils.show("请输入正确的手机号")
            return
        }

        if (loginType == 1 && it.code.isEmpty()) {
            ToastUtils.show("请输入验证码")
            return
        }
        if (loginType == 0 && it.password.isEmpty()) {
            ToastUtils.show("请输入密码")
            return
        }
        if (loginType == 0 && it.password.length < 6) {
            ToastUtils.show("请输入最少6位数的密码")
            return
        }
        if (!checked) {
            ToastUtils.show("请阅读并同意用户协议和隐私政策")
            return
        }
        val request = if (loginType == 0) LoginRequest(
            phone = it.phone,
            password = it.password.md5Encrypt()
        ) else LoginRequest(
            phone = it.phone,
            code = it.code
        )
        request(
            api = { if (loginType == 0) passwordLogin(request) else smsCodeLogin(request) },
            success = {
                AppStorage.token = it?.token
                UserStorage.user = it
                JPushHelper.setJPushAlias()
                mState.postEvent(LoginState.LoginSuccess)
            })
    }

    private fun fetchSmsCode(imageCode: String, phone: String) {
        if (phone.isEmpty() || phone.length < 11) {
            ToastUtils.show("请输入正确的手机号")
            return
        }
        if (imageCode.isEmpty()) {
            ToastUtils.show("请输入图形验证码")
            return
        }
        request(api = { smsCode(SendSmsCodeRequest(2, imageCode, phone)) }, success = {
            mState.postEvent(LoginState.SmdCodeSuccess)
        }, error = {
            showToast(it.message)
            getPicCode(phone)
        })
    }

    private fun lastVersion() {
        request(api = { lastVersion(VersionInfoRequest()) }, success = {
            if (it != null) {
                if (versionCode > 0 && versionCode < it.versionNum) {
                    mState.postEvent(LoginState.ShowDialog(it))
                }
            }

        }, error = {

        })
    }

    /**
     * 切换登录类型
     */
    fun changeLogin(type: Int) {
        loginType = type
    }

    private fun getPicCode(phone: String) {
        if (phone.isEmpty() || phone.length < 11) {
            ToastUtils.show("请输入正确的手机号")
            return
        }
        val url =
            "${ServerConfig.baseHost}api/web/auth/sms/sendpicVerifyCode?phone=${phone}&timestamp=${System.currentTimeMillis()}"
        viewModelScope.launch {
            mState.postEvent(LoginState.GetPicCodeSuccess(url))
        }

    }

}